#!/bin/bash

#need automake,autoconf,libtool,libssl-dev installed.
which automake
if [ 0 -ne $? ]; then
	echo "automake was not installed."
	exit 1
fi

which autoconf
if [ 0 -ne $? ]; then
	echo "autoconf was not installed."
	exit 1
fi

which libtoolize 
if [ 0 -ne $? ]; then
	echo "libtool was not installed."
	exit 1
fi
echo "automake & autoconf & libtool is installed."


currentdir=$(cd "$(dirname "$0")"; pwd)
echo "build directory: ${currentdir}."

echo -e "\nbuild libevent..."
if [ ! -d "$currentdir/build" ]; then 
	mkdir "$currentdir/build"
else
	rm -rf ${currentdir}/build/*
fi

 
NDK="/opt/android-toolchain-ndkr16b-arm64-24/bin"
# Tell configure what tools to use.
target_host=aarch64-linux-android
export AR=$NDK/$target_host-ar
export AS=$NDK/$target_host-as
export CC=$NDK/$target_host-clang
export CXX=$NDK/$target_host-clang++
export LD=$NDK/$target_host-ld
export RANLIB=$NDK/$target_host-ranlib
export STRIP=$NDK/$target_host-strip

# Tell configure what flags Android requires.
#export CFLAGS="-fPIE -fPIC"
#export LDFLAGS="-pie"	

autoreconf
./configure CFLAGS=-fPIC --disable-openssl --disable-samples --enable-shared=no --enable-function-sections --prefix=/usr/local --host $target_host
if [ $? -ne 0 ]; then exit 1; fi
make
make install DESTDIR=$currentdir/build

if [ ! -f "$currentdir/build/usr/local/lib/libevent_core.a" ]; then exit 1; fi
rm -rf ${currentdir}/../../../lib/libevent*.a
cp -v $currentdir/build/usr/local/lib/libevent_core.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_pthreads.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_extra.a ${currentdir}/../../../lib
if [ -f "$currentdir/build/usr/local/lib/libevent_openssl.a" ]; then
	cp -v $currentdir/build/usr/local/lib/libevent_openssl.a ${currentdir}/../../../lib
fi

make clean
rm -rf ${currentdir}/build/*

echo "====== libevent build success! ======"
exit 0
